package com.gzcstec.gateway.filter;

import com.gzcstec.gateway.constant.CookieConstants;
import com.gzcstec.gateway.constant.RedisConstants;
import com.gzcstec.gateway.enums.ExceptionEnums;
import com.gzcstec.gateway.exception.RateLimiterException;
import com.gzcstec.gateway.utils.CookieUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * 用户访问鉴权（区别买家和卖家）
 */
@Component
public class AuthorizeFilter extends ZuulFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        //不需要过滤，用BuyerAuthorizeFilter SellerAuthorizeFilter 替代
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        /*/buyer/order/create 买家访问
          /seller/order/finish 卖家访问
          /product/list 都可以访问
        */
        if("/order/order/buyer/create".equals(request.getRequestURI())) {
            //判断cookie里面是否有openid的cookie
            if(null == CookieUtils.get(request , CookieConstants.OPENID)) {
                //鉴权不通过
                requestContext.setSendZuulResponse(false);
                requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            }
        }

        if("/order/order/seller/finish".equals(request.getRequestURI())) {
            //判断cookie里面是否有openid的cookie
            Cookie cookie = CookieUtils.get(request , CookieConstants.TOKEN);
            //判断cookie是否为空，并且redis里面有相应的openid
            if(cookie == null ||
                    StringUtils.isEmpty(stringRedisTemplate.opsForValue().get(String.format(RedisConstants.TOKEN_TEMPLATE , cookie.getValue())))) {
                //鉴权不通过
                requestContext.setSendZuulResponse(false);
                requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            }

        }
        return null;
    }
}
